package com.chen.cglib;

import com.alibaba.fastjson.JSON;
import com.chen.api.RpcRequest;
import com.chen.api.RpcResponse;
import com.chen.filter.Filter;
import com.chen.netty.HttpClientHandler;
import com.chen.netty.NettyClient;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;
import java.lang.reflect.Method;

public class RpcMethodInterceptor implements MethodInterceptor {
    public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");

    private final Class<?> serviceClass;
    private final String url;
    private final Filter[] filters;

    public RpcMethodInterceptor(Class<?> serviceClass, String url, Filter[] filters) {
        this.serviceClass = serviceClass;
        this.url = url;
        this.filters = filters;
    }


    @Override
    public Object intercept(Object obj, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
        RpcRequest request = new RpcRequest();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(params);

        if (null != filters){
            for (Filter filter : filters){
                if (!filter.filter(request)){
                    return null;
                }
            }
        }

        HttpClientHandler httpClientHandler = new HttpClientHandler(request);
        new NettyClient("localhost",8080,httpClientHandler).send();
        RpcResponse response = httpClientHandler.getResponse();
        if (response.getException() != null){
            throw response.getException();
        }
        return JSON.parse(response.getResult().toString());
    }
}
